package controller;

import service.IUserService;
import service.impl.UserServiceImpl;
import utils.NoLoginUtil;
import utils.SecretUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "LoginServlet", value = "/login")
public class LoginServlet extends HttpServlet {
    private IUserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        NoLoginUtil.doVerify(request);
        request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String nickname = request.getParameter("nick-name");
        String password = request.getParameter("password");
        if (userService.isUserExistsByUsernameAndPassword(nickname, password)) {
            HttpSession session = request.getSession();
            session.setMaxInactiveInterval(60 * 60 * 24 * 7);
            session.setAttribute("username", nickname);
            Map<String, String> map = new HashMap<>();
            map.put("username", nickname);
            map.put("password", password);
            Cookie cookie = new Cookie("core-data", SecretUtil.encryptBase64(map.toString()));
            cookie.setMaxAge(60 * 60 * 24 * 7);
            response.addCookie(cookie);
            if (userService.isAdminByUsernameAndPassword(nickname, password)) {
                response.sendRedirect("/goodsAll.jsp");
                session.setAttribute("isAdmin", true);
            } else {
                response.sendRedirect("/");
            }
        } else {
            request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
        }
    }
}
